﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace FDSimpleModelGenerator.ImageCode
{
    /// <summary>
    /// 基础图片验证码
    /// </summary>
    public class BasicImageCode
    {
        private readonly int ChCodeBeg = 0x4E00;
        private readonly int ChCodeEnd = 0x9FA5;
        private readonly string BasicCode = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        private readonly int LetterWidth = 26;  //单个字体的宽度范围
        private readonly int LetterHeight = 30; //单个字体的高度范围
        private readonly static RNGCryptoServiceProvider _rand = new RNGCryptoServiceProvider();
        private readonly static byte[] Randb = new byte[4];
        private readonly int _codeLength, _codeChineseLength;
        private Font[] fonts =
        {
            new Font(new FontFamily("Times New Roman"),20 +Next(1),System.Drawing.FontStyle.Regular),
            new Font(new FontFamily("Georgia"), 20 + Next(1),System.Drawing.FontStyle.Regular),
            new Font(new FontFamily("Arial"), 20 + Next(1),System.Drawing.FontStyle.Regular),
            new Font(new FontFamily("Comic Sans MS"), 20 + Next(1),System.Drawing.FontStyle.Regular)
        };

        public BasicImageCode()
        {
        }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="codeLength">总长度</param>
        /// <param name="subChineseLength">其中中文长度</param>
        /// <param name="height">高度</param>
        public BasicImageCode(int codeLength, int subChineseLength = 0, int height = 30)
        {
            _codeLength = codeLength;
            _codeChineseLength = subChineseLength;
            LetterHeight = height;
        }

        /// <summary>
        /// 验证码
        /// </summary>
        public string Code { get; set; }

        /// <summary>
        /// 验证码图片
        /// </summary>
        public Bitmap Image { get; set; }

        /// <summary>
        /// 验证码图片数据
        /// </summary>
        public byte[] Buffer { get; set; }

        /// <summary>
        /// 获得下一个随机数
        /// </summary>
        /// <param name="max">最大值</param>
        private static int Next(int max)
        {
            _rand.GetBytes(Randb);
            int value = BitConverter.ToInt32(Randb, 0);
            value = value % (max + 1);
            if (value < 0) value = -value;
            return value;
        }

        /// <summary>
        /// 获得下一个随机数
        /// </summary>
        /// <param name="min">最小值</param>
        /// <param name="max">最大值</param>
        private static int Next(int min, int max)
        {
            int value = Next(max - min) + min;
            return value;
        }

        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <param name="length"></param>
        /// <param name="chSubLength">其中中文字个数</param>
        /// <returns></returns>
        public string RandCode(int length, int chSubLength)
        {
            var rand = new Random((int)DateTime.Now.Ticks % 100000000);
            var sb = new StringBuilder();
            for (var i = 0; i < length - chSubLength; ++i)
            {
                sb.Append(BasicCode[rand.Next(0, BasicCode.Length)]);
            }

            for (var i = 0; i < chSubLength; ++i)
            {
                sb.Append((char)rand.Next(ChCodeBeg, ChCodeEnd + 1));
            }

            // 打乱
            for (var i = 0; i < sb.Length; ++i)
            {
                var chIndex = rand.Next(0, sb.Length);
                var ch = sb[chIndex];
                var temp = sb[i];
                sb[i] = ch;
                sb[chIndex] = temp;
            }

            Code = sb.ToString();
            return Code;
        }

        /// <summary>
        /// 绘制验证码
        /// </summary>
        public void CreateImage()
        {
            if (string.IsNullOrEmpty(Code))
            {
                RandCode(4, 0); // 默认4位字母+数字
            }
            int intImageWidth = Code.Length * LetterWidth;
            Bitmap image = new Bitmap(intImageWidth, LetterHeight);
            Graphics g = Graphics.FromImage(image);
            g.Clear(Color.White);
            for (int i = 0; i < Code.Length; i++)
            {
                int x1 = Next(image.Width - 1);
                int x2 = Next(image.Width - 1);
                int y1 = Next(image.Height - 1);
                int y2 = Next(image.Height - 1);
                g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
            }
            int _x = -12, _y = 0;
            for (int intIndex = 0; intIndex < Code.Length; intIndex++)
            {
                string strChar = Code.Substring(intIndex, 1);
                var isChinese = IsChineseCh(strChar);
                var pad = isChinese ? 12 : 0;
                _x += Next(12 + pad, 16 + pad);
                _y = Next(-2, 2);
                strChar = Next(1) == 1 ? strChar.ToLower() : strChar.ToUpper();
                Brush newBrush = new SolidBrush(GetRandomColor());
                Point thePos = new Point(_x, _y);
                g.DrawString(strChar, fonts[Next(fonts.Length - 1)], newBrush, thePos);
            }
            for (int i = 0; i < 10; i++)
            {
                int x = Next(image.Width - 1);
                int y = Next(image.Height - 1);
                image.SetPixel(x, y, Color.FromArgb(Next(0, 255), Next(0, 255), Next(0, 255)));
            }
            image = TwistImage(image, true, Next(1, 3), Next(4, 6));
            g.DrawRectangle(new Pen(Color.LightGray, 1), 0, 0, intImageWidth - 1, LetterHeight - 1);
            Image = image;
            using var ms = new MemoryStream();
            image.Save(ms, ImageFormat.Jpeg);
            Buffer = ms.GetBuffer();
        }

        /// <summary>
        /// 是否汉字
        /// </summary>
        /// <param name="strChar"></param>
        /// <returns></returns>
        private bool IsChineseCh(string strChar)
        {
            char ch = strChar[0];
            var nCh = (int)ch;
            return ChCodeBeg <= nCh && nCh <= ChCodeEnd;
        }

        /// <summary>
        /// 字体随机颜色
        /// </summary>
        public Color GetRandomColor()
        {
            Random randomNumFirst = new Random((int)DateTime.Now.Ticks % 100000000);
            System.Threading.Thread.Sleep(randomNumFirst.Next(50));
            Random randomNumSencond = new Random((int)DateTime.Now.Ticks % 100000000);
            int intRed = randomNumFirst.Next(180);
            int intGreen = randomNumSencond.Next(180);
            int intBlue = (intRed + intGreen > 300) ? 0 : 400 - intRed - intGreen;
            intBlue = (intBlue > 255) ? 255 : intBlue;
            return Color.FromArgb(intRed, intGreen, intBlue);
        }

        /// <summary>
        /// 正弦曲线Wave扭曲图片
        /// </summary>
        /// <param name="srcBmp">图片路径</param>
        /// <param name="bXDir">如果扭曲则选择为True</param>
        /// <param name="nMultValue">波形的幅度倍数，越大扭曲的程度越高,一般为3</param>
        /// <param name="dPhase">波形的起始相位,取值区间[0-2*PI)</param>
        public Bitmap TwistImage(Bitmap srcBmp, bool bXDir, double dMultValue, double dPhase)
        {
            double PI = 6.283185307179586476925286766559;
            Bitmap destBmp = new Bitmap(srcBmp.Width, srcBmp.Height);
            Graphics graph = Graphics.FromImage(destBmp);
            graph.FillRectangle(new SolidBrush(Color.White), 0, 0, destBmp.Width, destBmp.Height);
            graph.Dispose();
            double dBaseAxisLen = bXDir ? (double)destBmp.Height : (double)destBmp.Width;
            for (int i = 0; i < destBmp.Width; i++)
            {
                for (int j = 0; j < destBmp.Height; j++)
                {
                    double dx = 0;
                    dx = bXDir ? (PI * (double)j) / dBaseAxisLen : (PI * (double)i) / dBaseAxisLen;
                    dx += dPhase;
                    double dy = Math.Sin(dx);
                    int nOldX = 0, nOldY = 0;
                    nOldX = bXDir ? i + (int)(dy * dMultValue) : i;
                    nOldY = bXDir ? j : j + (int)(dy * dMultValue);

                    Color color = srcBmp.GetPixel(i, j);
                    if (nOldX >= 0 && nOldX < destBmp.Width
                     && nOldY >= 0 && nOldY < destBmp.Height)
                    {
                        destBmp.SetPixel(nOldX, nOldY, color);
                    }
                }
            }
            srcBmp.Dispose();
            return destBmp;
        }
    }
}
